package validator;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import exceptions.InvalidEMailException;
import exceptions.RequiredEmailMissingException;

/**
 * Implements a validator of emails with regular expressions
 * @author Alexandre, Cristovao, Raul, Rodolpho, Tales
 * @version 1.1
 * @milestone Number 2
 */
public class EmailValidator {
	
	/**
	 * Checks if something was typed.
	 * @param email
	 * @throws RequiredEmailMissingException
	 */
	public static void checkMissing(String email) throws RequiredEmailMissingException{
		if (email.trim() == "" || email == null) {
			throw new RequiredEmailMissingException(
			"E-mail eh um dado obrigatorio.");
		}
	}
	
	/**
	 * Validates an email address with regular expression.
	 * @param email
	 * @throws InvalidEMailException
	 */
	public static void validateEmail(String email) throws InvalidEMailException{
		String expressaoRegular = "^[\\w\\-]([\\.\\w])+[\\w]+@([\\w\\-]+\\.)+[A-Z]{2,4}$";
		CharSequence emailChar = email;
		Pattern pattern = Pattern.compile(expressaoRegular,
				Pattern.CASE_INSENSITIVE);
		Matcher matcher = pattern.matcher(emailChar);
		if (!matcher.matches()){
			throw new InvalidEMailException("E-mail invalido.");
		}
	}
	
	/**
	 * Checks and valids an email address
	 * @param email
	 * @throws InvalidEMailException
	 * @throws RequiredEmailMissingException
	 */
	public static void checkAndValidateEmail(String email) throws InvalidEMailException, RequiredEmailMissingException{
		checkMissing(email);
		validateEmail(email);
	}

}
